import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Thread_tryLock {

    static final ReentrantLock lock  = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(new MyThread3(),"A").start();
        new Thread(new MyThread3(),"B").start();
    }

    static class MyThread3 extends Thread{
        @Override
        public void run() {
            try {
                if (lock.tryLock(2, TimeUnit.SECONDS)){
                    System.out.println(Thread.currentThread().getName()+"获取到锁");
                    Thread.sleep(3000);
                }else {
                    System.out.println(Thread.currentThread().getName()+"没有获取到锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

}
